# -*- coding = utf-8 -*-
# @Time    : 2025/3/28 下午8:29
# @Author  : yqk
# @File    : 多线程生产者和消费者.py
# @Software: PyCharm

import threading
import random
import time

lock = threading.Lock()
cycle_time = 10
count = 0
class Producer(threading.Thread):
    def run(self)->None:
        global total_money, cycle_time, count
        while True:
            lock.acquire()
            if count > cycle_time:
                print(f'{threading.current_thread().name}生产结束')
                lock.release()
                break
            money = random.randint(100, 5000)
            total_money += money
            count += 1
            print(f'{threading.current_thread().name}有{total_money}元')
            lock.release()
            time.sleep(0.5)
class Consumer(threading.Thread):
    def run(self)->None:
        global total_money
        while True:
            lock.acquire()
            money = random.randint(100, 5000)
            if total_money > money:
                total_money -= money
                print(f'{threading.current_thread().name}消费{money}元')
            else:
                if count > cycle_time:
                    print(f'{threading.current_thread().name}消费结束')
                    lock.release()
                    break
                print(f'{threading.current_thread().name}消费失败, 余额不足有{total_money}元')
            lock.release()

def main():
    global total_money
    total_money = 0
    for i in range(5):
        Producer(name=f'生产者{i}').start()
    for i in range(5):
        Consumer(name=f'消费者{i}').start()

if __name__ == '__main__':
    main()